<?php

class AliLoginAction extends CommonAction {
	
	public $cmTableName = 'AliLogin';
	public $output      = '';
	
	
	//初始化方法，所有方法必须传 :sessionKey  引入SDK入口文件
	public function _initialize(){
		
		
	}
	
	
	
	
	
	//返回处理方法
	public function returnData($data){
		
		header("Access-Control-Allow-Origin: *");
		header("Content-type: text/html; charset=utf-8");
		echo json_encode($data);exit;
	}
	
	
	
	
	public function login_index(){
		
		$type = empty( $_REQUEST['type'] ) ? 0 :  $_REQUEST['type'] ;
		
		$appKey    = APP_KEY;
		$appSecret = APP_SECRET;
		
		// 1为正式，2为测试   
		//  http://axure.tiansblog.com/taobao-sdk/test2.php
		if($type=='1'){
			
			$url="https://oauth.alibaba.com/authorize?response_type=code&client_id=".$appKey."&redirect_uri=http://t.ihecha.me/index.php/AliLogin/login_redirect&state=1&sp=icbu";
		}
		
		if($type=='2'){
			
			$url="https://oauth.alibaba.com/authorize?response_type=code&client_id=".$appKey."&redirect_uri=http://t.ihecha.me/index.php/AliLogin/login_redirect&state=2&sp=icbu";
		}
		
		
		
		
		Header("Location: $url"); 
	}
	
	public function login_redirect(){
		
	
		
		$state = $_REQUEST['state'];
		$app   = $_REQUEST['k'];
		
		//session_start();
		
		header("Content-type: text/html; charset=utf-8"); 
	
		$appKey    = APP_KEY;
		$appSecret = APP_SECRET;
		
		
		
		$url = 'https://oauth.alibaba.com/token';

		$postfields= array(
			'grant_type' => 	'authorization_code',
			'client_id' => 		$appKey,
			'client_secret' => 	$appSecret,
			'code'		=>		$_GET['code'],
			'redirect_uri'	=>	APP_REDIRECT
		);
		 
		$post_data = '';
		
		foreach($postfields as $key=>$value){
			 
		$post_data .="$key=".urlencode($value)."&";
		}
		 
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
		 
		//指定post数据
		curl_setopt($ch, CURLOPT_POST, true);

		//添加变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
		$output = curl_exec($ch);
		$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		//echo $httpStatusCode;
		curl_close($ch);
		
		$userInfo = json_decode($output,true);
		
		//$_SESSION['AliUserInfo'] = $userInfo;
		
		$memberInfo = M('member')->where('username="'.$userInfo['user_nick'].'"')->find();
		
		$radom_code = md5(md5(time().MD5KEY));
		
		
		$k 		   = empty($_REQUEST['k'])?'':$_REQUEST['k'];
		
		$AppInfo   = getAppInfoByK($k);
		$accessKey = getAppAccessKey($k);
		
		if(empty($memberInfo)){
			
			$dataNewMem   = array();
			$dataNewMem['username'] 		= $userInfo['user_nick'];
			//$dataNewMem['addtime']  		= time();
			//$dataNewMem['endtime']  		= intval($userInfo['expire_time']/1000);
			
			$dataNewMem[$AppInfo['startKey']] = time();
			$dataNewMem[$AppInfo['endKey']]   = intval($userInfo['expire_time']/1000);
			
			$dataNewMem['username_md5'] 	= md5(md5($userInfo['user_nick'].MD5KEY));
			$dataNewMem['is_trusteeship']   = 1;
			
			$dataNewMem['radom_code']       = $radom_code;
			$dataNewMem['last_login_time']  = time();
			$dataNewMem[$AppInfo['priority']]  = 1;
			$dataNewMem[$AppInfo['accessKey']]         = $userInfo['access_token'];
			$res = M('member')->add($dataNewMem);
			
			$memberInfo = M('member')->where('username="'.$dataNewMem['username'].'"')->find();
			
			if( !empty($memberInfo['username_md5']) && !empty($memberInfo['radom_code']) ){
				
				$url = 'http://118.178.234.34:30004/priority/sendEmail?u='.$memberInfo['username_md5'].'&r='.$memberInfo['radom_code'];
			
				file_get_contents($url);
			}
		}else{
			
			$dataSaveMem  = array();
			$dataSaveMem['member_id'] 		 = $memberInfo['member_id'];
			//$dataSaveMem['endtime'] 		 = intval($userInfo['expire_time']/1000);
			$dataSaveMem['radom_code']       = $radom_code;
			$dataSaveMem['last_login_time']  = time();
			$dataSaveMem[$AppInfo['accessKey']]         = $userInfo['access_token'];
			$dataSaveMem[$AppInfo['priority']]  = 1;
			
			$dataSaveMem[$AppInfo['endKey']] = intval($userInfo['expire_time']/1000);
			
			if( $memberInfo[$AppInfo['startKey']]==0 ){
				
				$dataSaveMem[$AppInfo['startKey']] = time();
			}
			
			
			$res = M('member')->save($dataSaveMem);
			
		}
		
		$memberInfo = M('member')->where('username="'.$userInfo['user_nick'].'"')->find();
		
		if($memberInfo['status']==1){
			
			echo '';exit;
		}
		
		$this->assign('userInfo',$output);
		$this->assign('memberName',$memberInfo['username_md5']);
		$type='0';   //0为正式环境   1为测试环境
		if(!empty($userInfo['access_token'])){
			if($state=='1' ){
				
				$type = '1';
			}
			//$_SESSION['output'] = $output;
			//AAA($memberInfo);
			$this->redirect('AliLogin/index',array('u'=>$memberInfo['username_md5'],'r'=>$radom_code,'type'=>$type,'k'=>$app));
		}
		
		exit;
		
		
		if($state=='1'){
			
			//$str = $this->fetch('../../dist/index'); 
			
			$str = file_get_contents('./dist/index.html');
			
			$str = str_replace('./','http://t.ihecha.me/dist/',$str);
			//file_put_contents('./1.txt',$str);
			$str = str_replace('<body>','<body>'.'<input type="hidden" id="shenche_userInfo"  name="shenche_userInfo"  value=\''.$output.'\' />',$str);
			//file_put_contents('./t2.txt',$str);
			echo $str;
			exit;
		}else{
			
			echo $output;exit;
		}
		
		
		//$this->assgin('loginInfo',$output);
	}
	
	public function testMail(){
		
		
		$content = '时间：'.date('Y年m月d日 H:i:s',time());
		$content = iconv('UTF-8','gb18030',$content);
		
		
		$title   = '用户名称：gdhct, 到期时间：';
		$title   = iconv('UTF-8','gb18030',$title);
		
		sendmail('710735664@qq.com',$title,$content);
		//sendmail('469572708@qq.com',$title,$content);
		
		AAA('yyyyyyyyyyyyyyyyyt');
	}
	
	
	
	public function delOldRecord(){
		
		//$where = '';
		//$where = '('.time().'  - datetime) > 86400 ';
		
		$sql = 'delete from precord where ('.time().' - `datetime` ) > 86400';
		
		$res = M()->query($sql);
		
		die(json_encode($res));
	}
	
	public function index(){
		
		//$output = $_SESSION['output'];
		$output = '';
		//echo 'asdfasdfasdf';
			


//setcookie("asdsdf",'www.sunphp.org',time()+3600*24);
		$str = file_get_contents('./dist/index.html');
			
		$str = str_replace('./','http://t.ihecha.me/dist/',$str);
		
		$str = str_replace('<body>','<body>'.'<input type="hidden" id="shenche_userInfo"  name="shenche_userInfo"  value=\''.$output.'\' />',$str);
		
		echo $str;	
		
		exit;
	}
	
	
	
	
	
	
	
	
	
	
   
	
	
	
	
	
	
	
	
	
	
}

?>